package tech.mhuang.pacebox.springboot.core.spring.util;

import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tech.mhuang.pacebox.core.convert.Converter;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.springboot.protocol.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * spring工具类
 *
 * @author mhuang
 * @since 1.0.0
 */
public class SpringServletUtil {

    /**
     * 获取RequestAttributes
     *
     * @return ServletRequestAttributes
     */
    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取请求参数值
     *
     * @param name 参数
     * @return 值
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取请求参数值，不存在则默认
     *
     * @param name         参数
     * @param defaultValue 默认值
     * @return 最终值
     */
    public static String getParameter(String name, String defaultValue) {
        return Converter.str(getParameter(name), defaultValue);
    }

    /**
     * 获取请求参数值带转换数据类型
     *
     * @param name  参数
     * @param clazz 参数值类型
     * @param <T>   参数值泛型
     * @return 参数值
     */
    public static <T> T getParameterAsType(String name, Class<T> clazz) {
        return Converter.convert(clazz, getParameter(name), null);
    }

    /**
     * 获取session
     *
     * @return HttpSession
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取HttpServletResponse
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 应答数据
     *
     * @param str 数据
     * @return null
     */
    public static String resultStr(String str) {
        return resultStr(getResponse(), str);
    }

    /**
     * 应答数据
     *
     * @param response HttpServletResponse
     * @param str      数据
     * @return null
     */
    public static String resultStr(HttpServletResponse response, String str) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().write(str);
        } catch (IOException e) {
            throw new BusinessException(Result.SYS_FAILD, Result.FAILD_MSG);
        }
        return null;
    }
}